<template>
    <div class="operator-view">
        <el-row align="middle" class="toolbar" :gutter="16" style="margin-bottom:12px;">
            <el-col :span="16">
                <el-input v-model="searchForm.nickname" placeholder="姓名" style="width:200px;margin-right:8px;" clearable />
                <el-input v-model="searchForm.phone" placeholder="手机号" style="width:200px;margin-right:8px;" clearable />
                <el-select v-model="searchForm.roleId" placeholder="角色" style="width:200px;margin-right:8px;" clearable>
                    <el-option v-for="r in rolesForSelect" :key="r.id" :label="r.roleName" :value="r.id" />
                </el-select>
                <el-button type="primary" @click="fetchUsers">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </el-col>
            <el-col :span="8" style="text-align:right;">
                <el-button type="primary" @click="onAdd">新增</el-button>
                <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">删除</el-button>
            </el-col>
        </el-row>

        <el-table :data="users" v-loading="loading" element-loading-text="加载中..." @selection-change="handleSelectionChange" style="width:100%;">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="nickname" label="姓名" min-width="140" />
            <el-table-column prop="companyName" label="公司名称" min-width="160" />
            <el-table-column prop="phone" label="手机号" min-width="140" />
            <el-table-column prop="roleName" label="角色名称" min-width="140" />
            <el-table-column prop="createdAt" label="创建时间" min-width="180">
                <template #default="{ row }">
                    <span>{{ formatDate(row.createdAt) }}</span>
                </template>
</el-table-column>
<el-table-column prop="isDeleted" label="状态" min-width="100">
    <template #default="{ row }">
                    <el-tag type="info" v-if="!row.isDeleted">启用</el-tag>
                    <el-tag type="danger" v-else>已删除</el-tag>
                </template>
</el-table-column>
<el-table-column label="操作" fixed="right" width="220">
    <template #default="{ row }">
                    <el-button type="text" size="small" @click="onView(row)">查看</el-button>
                    <el-button type="text" size="small" @click="onEdit(row)">编辑</el-button>
                    <el-button type="text" size="small" style="color:#f56c6c" @click="handleDelete(row)">删除</el-button>
                </template>
</el-table-column>
</el-table>

<el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size="pageSize"
    :current-page.sync="page" @size-change="onPageSizeChange" @current-change="onPageChange"
    style="margin-top:12px; text-align:right;" />
</div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import axios from 'axios'

const API_BASE = '/api/SystemManagement/UserShow' // 根据后端实际地址替换
const ROLE_API = '/api/SystemManagement/RoleShow'

const loading = ref(false)
const users = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const multipleSelection = ref([])

const searchForm = reactive({ nickname: '', phone: '', roleId: null })

const roles = ref([])
const rolesForSelect = computed(() => roles.value.map(r => ({ id: r.id, roleName: r.roleName })))

function formatDate(value) {
    if (!value) return ''
    const d = new Date(value)
    return d.toLocaleString()
}

function handleSelectionChange(val) {
    multipleSelection.value = val
}

async function fetchRoles() {
    try {
        const res = await axios.get(ROLE_API)
        const payload = res.data || res
        if (payload && payload.data) roles.value = payload.data.items || payload.data || []
        else if (Array.isArray(payload)) roles.value = payload
        else roles.value = payload.items || []
    } catch (err) {
        console.error('fetchRoles error', err)
    }
}

async function fetchUsers() {
    loading.value = true
    try {
        const params = { pageindex: page.value, pageSize: pageSize.value, nickname: searchForm.nickname, phone: searchForm.phone }
        if (searchForm.roleId) params.roleId = searchForm.roleId
        const res = await axios.get(API_BASE, { params })
        const payload = res.data || res
        const list = payload.data?.items || payload.data || payload.items || payload || []
        users.value = (list || []).map((x) => ({
            id: x.id ?? x.Id,
            nickname: x.nickname ?? x.Nickname,
            companyName: x.companyName ?? x.CompanyName ?? '',
            phone: x.phone ?? x.Phone,
            roleName: x.roleName ?? x.RoleName ?? (x.role?.roleName) ?? '',
            createdAt: x.createdAt ?? x.CreatedAt,
            isDeleted: x.isDeleted ?? x.IsDeleted ?? false,
        }))
        total.value = payload.data?.total || payload.total || users.value.length
    } catch (err) {
        console.error('fetchUsers error', err)
    } finally {
        loading.value = false
    }
}

function resetSearch() {
    searchForm.nickname = ''
    searchForm.phone = ''
    searchForm.roleId = null
}

function onAdd() {
    // 打开新增对话（由产品或后续实现）
    console.log('新增')
}

function onView(row) {
    console.log('查看', row)
}

function onEdit(row) {
    console.log('编辑', row)
}

async function handleDelete(row) {
    try {
        const id = row.id
        await axios.delete(`${API_BASE}/${id}`)
        fetchUsers()
    } catch (err) {
        console.error('delete user error', err)
    }
}

async function handleBatchDelete() {
    if (!multipleSelection.value.length) return
    const ids = multipleSelection.value.map(r => r.id)
    try {
        await axios.delete(API_BASE, { data: { ids } })
        fetchUsers()
    } catch (err) {
        console.error('batch delete error', err)
    }
}

function onPageSizeChange(size) {
    pageSize.value = size
    fetchUsers()
}

function onPageChange(p) {
    page.value = p
    fetchUsers()
}

onMounted(() => {
    fetchRoles()
    fetchUsers()
})
</script>

<style scoped>
.toolbar {
    margin-bottom: 12px
}

.operator-view .el-table .cell {
    white-space: nowrap
}
</style>